package org.jfsm.core;

import org.jfsm.concurrent.*;

class ConcurrentFSMWorker extends FSMWorker {

    private static final class Runner implements ConcurrentRunner {
        private final int eventID;
        private final Object message;
        private final FSMWorker worker;

        private Runner(FSMWorker worker, int eventID, Object message) {
            this.eventID = eventID;
            this.message = message;
            this.worker = worker;
        }

        public final void run(ConcurrentContext context) {
            worker.run((InstanceState) context, eventID, message);
        }

        @Override
        public String toString() {
            return message != null ? message.toString() : ("" + eventID);
        }

    }

    private final ContextExecutor executor;

    ConcurrentFSMWorker(BaseTransitionMap<?> tm, ContextExecutor executor) throws FSMException {
        super(tm);
        this.executor = executor;
    }

    @Override
    void submit(InstanceState context, int eventID, Object message) {
        executor.submit((ConcurrentFSMContext) context, new Runner(this, eventID, message));
    }

    @Override
    Object createWork(int eventID, Object message) {
        return new Runner(this, eventID, message);
    }

    @Override
    void submit(InstanceState context, Object work) {
        Runner runner = (Runner) work;
        executor.submit((ConcurrentFSMContext) context, runner);
    }
}
